/**
 * Copyright (c) 2017 ShopJsp. All Rights Reserved.
 * ============================================================================
 * 版权所有 2011 - 今 北京华宇盈通科技有限公司，并保留所有权利。
 * ----------------------------------------------------------------------------
 * 提示：在未取得SHOPJSP商业授权之前，您不能将本软件应用于商业用途，否则SHOPJSP将保留追究的权力。
 * ----------------------------------------------------------------------------
 * 官方网站：http://www.shopjsp.com
 * ============================================================================
 * @author Wang Youchun on 2017/04/26 0024上午 11:19.
 */

package com.hyyt.shopjsp.shiro.filter;

import com.hyyt.shopjsp.basic.pojo.BasicUsers;
import com.hyyt.shopjsp.util.common.LoggerUtils;
import com.hyyt.shopjsp.util.common.StringStaticKey;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * 登录校验
 */
public class LoginFilter extends AccessControlFilter {
    final static Class<LoginFilter> CLASS = LoginFilter.class;

    @Override
    protected boolean isAccessAllowed(ServletRequest request,ServletResponse response, Object mappedValue) throws Exception {
        Subject subject = getSubject(request, response);
        BasicUsers user = (BasicUsers) subject.getSession().getAttribute(StringStaticKey.SESSION_USERS);
        if (null != user || isLoginRequest(request, response)) {// && isEnabled()
            return Boolean.TRUE;
        }
        if (ShiroFilterUtils.isAjax(request)) {// ajax请求
            Map<String, String> resultMap = new HashMap<String, String>();
            LoggerUtils.info(getClass(), "当前用户没有登录，并且是Ajax请求！");
            resultMap.put("login_status", "300");
            //resultMap.put("message", "\u5F53\u524D\u7528\u6237\u6CA1\u6709\u767B\u5F55\uFF01");//当前用户没有登录！
            resultMap.put("message", "当前用户没有登录！");//当前用户没有登录！
            ShiroFilterUtils.out(response, resultMap);
        }
        return Boolean.FALSE;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        //保存Request和Response 到登录后的链接
        saveRequestAndRedirectToLogin(request, response);
        return Boolean.FALSE;
    }


}
